const path = require('path')
const webpack = require('webpack')
const GitRevisionPlugin = require('git-revision-webpack-plugin')
const GitRevision = new GitRevisionPlugin()
const buildDate = JSON.stringify(new Date().toLocaleString())
const createThemeColorReplacerPlugin = require('./config/plugin.config')

function resolve (dir) {
  return path.join(__dirname, dir)
}

const isProd = process.env.NODE_ENV === 'production'

const assetsCDN = {
  // webpack build externals
  externals: {
    vue: 'Vue',
    'vue-router': 'VueRouter',
    vuex: 'Vuex',
    axios: 'axios'
  },
  css: [],
  // https://unpkg.com/browse/vue@2.6.10/
  js: [
    '//cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.min.js',
    '//cdn.jsdelivr.net/npm/vue-router@3.1.3/dist/vue-router.min.js',
    '//cdn.jsdelivr.net/npm/vuex@3.1.1/dist/vuex.min.js',
    '//cdn.jsdelivr.net/npm/axios@0.19.0/dist/axios.min.js'
  ]
}

// vue.config.js
const vueConfig = {
  publicPath: '/sfapprove-web/',
  configureWebpack: {
    // webpack plugins
    plugins: [
      // Ignore all locale files of moment.js
      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
      new webpack.DefinePlugin({
        APP_VERSION: `"${require('./package.json').version}"`,
        GIT_HASH: JSON.stringify(GitRevision.version()),
        BUILD_DATE: buildDate
      })
    ],
    // 把chunk-vendors.js进行分包，提升资源加载速度，很有必要
    // optimization: {
    //     /**
    //      * runtimeChunk可选值有：true或'multiple'或'single'
    //      * true或'multiple'会有每个入口对应的chunk。不过一般情况下
    //      * 考虑到要模块初始化，设置为single就够多数情况下使用啦。
    //      * 详情见官网：https://webpack.docschina.org/configuration/optimization/#optimizationruntimechunk
    //      * */
    //     runtimeChunk: 'single',
    //     /**
    //      * 以前是CommonsChunkPlugin，现在换成optimization.splitChunks。普通项目下方的配置就足够用啦
    //      * 详情见官网：https://webpack.docschina.org/configuration/optimization/#optimizationsplitchunks
    //      * */
    //     splitChunks: {
    //         chunks: 'all', // 可选值：all，async 和 initial。all功能最强大，所以咱们就使用all
    //         maxInitialRequests: Infinity, // 最大并行请求数，为了以防万一，设置无穷大即可
    //         minSize: 20000, // 引入的模块大于20kb才做代码分割，官方默认20000，这里不用修改了
    //         maxSize: 60000, // 若引入的模块大于60kb，则告诉webpack尝试再进行拆分
    //         cacheGroups: {
    //             vendors: {
    //                 test: /[\\/]node_modules[\\/]/, // 使用正则匹配node_modules中引入的模块
    //                 priority: -10, // 优先级值越大优先级越高，默认-10，不用修改
    //                 name(module) { // 设定分包以后的文件模块名字，按照包名字替换拼接一下
    //                     const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
    //                     return `npm.${packageName.replace('@', '')}`
    //                 },
    //             },
    //         },
    //     }
    // },
    // if prod, add externals
    // externals: isProd ? assetsCDN.externals : {}
    externals: {},
    devtool: 'cheap-module-source-map'
  },

  chainWebpack: (config) => {
    config.resolve.alias
      .set('@$', resolve('src'))

    const svgRule = config.module.rule('svg')
    svgRule.uses.clear()
    svgRule
      .oneOf('inline')
      .resourceQuery(/inline/)
      .use('vue-svg-icon-loader')
      .loader('vue-svg-icon-loader')
      .end()
      .end()
      .oneOf('external')
      .use('file-loader')
      .loader('file-loader')
      .options({
        name: 'assets/[name].[hash:8].[ext]'
      })

    // 添加地图key常量
    config.plugin('html').tap(args => {
      // 添加初始化变量
      args[0].MAP_KEY = process.env.VUE_APP_MAP_KEY
      return args
    })


    // if prod is on
    // assets require on cdn
    // if (isProd) {
    //   config.plugin('html').tap(args => {
    //     args[0].cdn = assetsCDN
    //     return args
    //   })
    // }
  },

  css: {
    loaderOptions: {
      less: {
        modifyVars: {
          // less vars，customize ant design theme

          // 'primary-color': '#F5222D',
          // 'link-color': '#F5222D',
          'border-radius-base': '2px'
        },
        // DO NOT REMOVE THIS LINE
        javascriptEnabled: true
      }
    }
  },

  devServer: {
    // development server port 8000
    port: 8000,
    headers: {			// 重点1: 允许跨域访问子应用页面
      'Access-Control-Allow-Origin': '*',
    }
    // If you want to turn on the proxy, please remove the mockjs /src/main.jsL11
    // proxy: {
    //   '/api': {
    //     target: 'https://mock.ihx.me/mock/5baf3052f7da7e07e04a5116/antd-pro',
    //     ws: false,
    //     changeOrigin: true
    //   }
    // }
  },

  // disable source map in production
  productionSourceMap: false,
  lintOnSave: false,
  // babel-loader no-ignore node_modules/*
  transpileDependencies: [],
  runtimeCompiler: true
}

// preview.pro.loacg.com only do not use in your production;
if (process.env.VUE_APP_PREVIEW === 'true') {
  console.log('VUE_APP_PREVIEW', true)
  // add `ThemeColorReplacer` plugin to webpack plugins
  vueConfig.configureWebpack.plugins.push(createThemeColorReplacerPlugin())
}

module.exports = vueConfig
